package com.huarun.module.login.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huarun.common.BaseController;
import com.huarun.common.HeadAuthorization;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.HttpUtil;
import com.huarun.common.util.LoginWelinkSigUtil;
import com.huarun.common.util.MyException;
import com.huarun.common.util.PropertyUtil;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.ResultCodeValue;
import com.huarun.common.util.UrlLib;
import com.huarun.faseplus.SubjectBean;
import com.huarun.module.sys.service.ISubjectService;
import com.huarun.module.sys.util.UserInfoUtil;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;
import com.huarun.redis.RedisKeyPrefix;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author hqy
 * @创建时间 2018-10-17 15:50
 * @Description 登入
 */
@RestController
@RequestMapping("login")
@Api(description = "登入")
@ApiIgnore
public class LoginController extends BaseController {
	@Resource
	private IUserService userService;
	
	@Resource
	private ISubjectService subjectService;

	private Logger logger = Logger.getLogger(LoginController.class);

	// 用code换取sessionKey
	@ApiOperation(notes = "用code换取sessionKey", httpMethod = "GET", value = "用code换取sessionKey")
	@RequestMapping(value = "/jsCode2Session", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<HeadAuthorization> jsCode2Session(@RequestParam String code,
			HttpServletRequest req) throws IOException {
		if (null == code) {
			throw new MyException(ResultCodeValue.R_PARAM_REQUIRED, "参数不能为空");
		}
		return userService.getSessionKey(code, req);

	}

	// 登录注册
	@ApiOperation(notes = "前端传递用户信息给后台", httpMethod = "GET", value = "前端传递用户信息给后台")
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<String> getUserInfo(@RequestParam String iv,
											   @RequestParam String encryptedData, HttpServletRequest req) throws IOException {
		if (StringUtils.isBlank(encryptedData)) {
			throw new MyException(ResultCodeValue.R_ENCRYPTED_DATA_ERROR, "请求中加密数据不存在");
		}
		if (StringUtils.isBlank(iv)) {
			throw new MyException(ResultCodeValue.R_IV_IS_NULL, "请求的加密偏移量为空");
		}
		try {
			return userService.saveUserPhone(encryptedData, iv, req);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new MyException(ResultCodeValue.R_ERROR, "系统错误，请联系管理员");
		}
	}

	@ApiOperation(value = "选择项目", notes = "选择项目")
	@RequestMapping(value = "/selectProject", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<User> selectProject(HttpServletRequest request) {
		try {
			return userService.saveUserInfo(request);
		}catch(Exception e) {
			e.printStackTrace();
			throw new MyException(ResultCodeValue.R_USERINFO_IS_NULL, "系统错误，请联系管理员");
		}
	}

	// 登录注册
	@ApiOperation(notes = "前端传递用户信息给后台", httpMethod = "POST", value = "前端传递用户信息给后台")
	@RequestMapping(value = "/decryptInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<String> decryptInfo(@RequestBody Map<String, Object> map, HttpServletRequest req)
			throws IOException {

		if (null == map || null == req.getHeader("openId")) {
			throw new MyException(ResultCodeValue.R_PARAM_REQUIRED, "参数不能为空");
		}
		String iv = (String) map.get("iv");
		String encryptedData = (String) map.get("encryptedData");
		if (StringUtils.isBlank(req.getHeader("openId"))) {
			throw new MyException(ResultCodeValue.R_OPENID_NOT_FOUND, "请求中的openId找不到");
		}
		if (StringUtils.isBlank(encryptedData)) {
			throw new MyException(ResultCodeValue.R_ENCRYPTED_DATA_ERROR, "请求中加密数据不存在");
		}
		if (StringUtils.isBlank(iv)) {
			throw new MyException(ResultCodeValue.R_IV_IS_NULL, "请求的加密偏移量为空");
		}
		return userService.decryptInfo(encryptedData, iv, req);
	}

	/**
	 * 登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/unauth", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage unauth() {
		return getOperResultMap(ResultCodeValue.R_AUTHOR_REQUIRED, "未登录");
	}

	@ApiOperation(notes = "后台登录微瓴", httpMethod = "GET", value = "后台登录微瓴地图平台")
	@RequestMapping(value = "/loginWelink", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Map<String, Object>> loginWelink() {
		ResponseMessage<Map<String, Object>> data = new ResponseMessage<Map<String, Object>>();
		try {
			/** 1. 获取参数 **/
			Integer appid = Integer.parseInt(Constant.WELINK_APP_ID);
			String key = Constant.WELINK_APP_TICKET;
			Long time = System.currentTimeMillis();
			Long num = new Double(Math.random() * 1000).longValue();// 1l;
			// 生成sig
			String sig = LoginWelinkSigUtil.encrypt(Constant.WELINK_APP_KEY, time, num);
			/** 2. 调用微瓴接口登录 **/
			String uri = Constant.WELINK_LOGIN_URI;
			String url = uri + "?time=" + time + "&num=" + num + "&sig=" + sig + "&appid=" + appid + "&app_ticket="
					+ key;
			log.info("登录微瓴后台uri：" + url);
			/** 3. 获取返回数据 **/
			String result = HttpUtil.doGet(url);
			JSONObject resultobj = JSONObject.parseObject(result);
			
			data = resultobj.toJavaObject(resultobj, ResponseMessage.class);
			if (data != null && data.getCode() == 0) {// 微瓴返回成功状态码为0，转换为200
				data.setCode(200);
			}
		} catch (Exception e) {
			data.setCode(ResultCodeValue.R_ERROR);
			data.setMessage("后台登录微瓴失败");
			e.printStackTrace();
		}
		data.setCode(200);
		return data;
	}

	public static void main(String[] args) {
		System.out.println(new Date(1545295810611L));

	}
	
//	
//	@ApiOperation(value = "获取face++信息", notes = "登录获取face++信息")
//	@RequestMapping(value = "/subjectList", method = RequestMethod.GET)
//	@ResponseBody
//	public  String subjectList(HttpServletRequest request) {
//		String uri = PropertyUtil.getProperty("face_url_B");
//		String url = uri + PropertyUtil.getProperty("getSubjectList");
//		Map<String, String> params = new HashMap<>();
//		// 'employee' - 员工; 'visitor' - 所有访客; 'vip' - VIP访客
//		params.put("category", "employee");
//		try {
//			byte[] resultJson = UrlLib.doGet(url, params);
//			String resultStr = new String(resultJson, "UTF-8");
//			SubjectBean subject = JSON.parseObject(resultStr, SubjectBean.class);// jsonString转为java对象
//
//			if (null != subject) {
//				int taotal = subject.getPage().getTotal();
//				for (int i = 1; i <= taotal; i++) {
//					params.put("page", i + "");
//					params.put("count", 10 + "");
//					byte[] subJson = UrlLib.doGet(url, params);
//					SubjectBean subSubjectBean = JSON.parseObject(new String(subJson, "UTF-8"), SubjectBean.class);
//					if (null != subSubjectBean) {
//						System.out.println(subSubjectBean.getData().size() + "----------page: " + i);
//						
//					}
//
//				}
//			}
//
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return null;
//	}


}
